import { nearest_param, nearest_datacontainer } from "./nearest.mjs";

export default function (container, datapath, value) {
  if (!datapath) return;

  if (datapath[0] === ":") {
    //在param中查找；
    let key = datapath.substring(1);
    // console.log({ datapath, key });
    return nearest_param(container)[key];
  } else {
    // 在data中查找；
    let patharray = datapath.split("/");

    let data;
    if (container.nodeName) {
      let datacontainer = nearest_datacontainer(container);
      // console.log({ datacontainer });
      if (!datacontainer) return undefined;
      data = datacontainer.thin_data;
    } else {
      data = container;
    }

    while (patharray.length > 1) {
      let path = patharray.shift();
      if (path === "..") {
        datacontainer = nearest_datacontainer(datacontainer.parentNode);
        data = datacontainer.thin_data;
        if (!datacontainer) return undefined;
      } else if (path === ".") {
        return data;
      } else {
        if (value !== undefined && data[path] === undefined) data[path] = {};
        data = data[path];
        if (data === undefined) return undefined;
      }
    }
    let path = patharray.shift();
    if (path === ".") {
      if (value !== undefined) data = value;
      return data;
    } else {
      // console.log({ value, data, path });
      if (value !== undefined) data[path] = value;
      return data ? data[path] : undefined;
    }
  }
}
